package com.meizu.hjcool7.androidorm;

import java.util.List;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper
{	
	private SqliteDB mWritableDb;
	private SqliteDB mReadableDb;
	
	public DBHelper(Context context, String name, int version)
	{
		super(context, name, null, version);
	}
	
	public static void createTable(SqliteDB db,Class<?>[] entities)
	{
		List<String> sqls = Util.getCreateSqls(entities);
		db.beginTransaction();
		try
		{
			for(String sql : sqls)
			{
				db.execSql(sql);
			}
			db.setTransactionSuccessful();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			db.endTransaction();
		}
	}
	
	public void onCreate(SqliteDB db)
	{

	}
	
	public void onOpen(SqliteDB db)
	{
		
	}
	
	public void onUpgrade(SqliteDB db, int oldVersion, int newVersion)
	{
		for (int i = oldVersion + 1;i <= newVersion;i++)
		{
			this.onUpgrade(db, i);
		}
	}
	
	public void onUpgrade(SqliteDB db,int version)
	{
		
	}
	
	@Override
	public void onOpen(SQLiteDatabase db)
	{
		this.onOpen(new SqliteDB(db));
	}

	@Override
	public void onCreate(SQLiteDatabase db)
	{
		this.onCreate(new SqliteDB(db));
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		onUpgrade(new SqliteDB(db), oldVersion, newVersion);
	}
	
	public SqliteDB getWritableDB()
	{
		if (mWritableDb == null)
		{
	        synchronized (this)
	        {
	        	if (mWritableDb == null)
	        	{
	        		mWritableDb = new SqliteDB(getWritableDatabase());
	        	}
	        }
		}
		return mWritableDb;
	}
	
	public SqliteDB getReadableDB()
	{
		if (mReadableDb == null)
		{
	        synchronized (this)
	        {
	        	if (mReadableDb == null)
	        	{
	        		mReadableDb = new SqliteDB(getReadableDatabase());
	        	}
	        }
		}
		return mReadableDb;
	}
}
